package com.aids_malaria.ui.datacollect;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.adapter.VillageSelectAdapter;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.event.Events;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.AreaC;
import com.aids_malaria.http.response.AreaV;
import com.aids_malaria.http.response.WorkAreaResponse;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.widget.titlebar.TitleBar;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class VillageSelectActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_county_name)
    TextView et_county_name;
    @BindView(R.id.et_village_name)
    EditText et_village_name;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    private List<AreaV> mData = new ArrayList<>();
    private List<AreaV> mOriginalData = new ArrayList<>();
    private VillageSelectAdapter villageSelectAdapter;
    private String countyCode = "";

    private int type;
    private boolean isCurrentArea;//是否现住址，是则只能选择设置了的工作区域

    @Override
    protected int getLayoutId() {
        return R.layout.activity_village_select;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitleBar(title_bar, ResourceUtil.getString(R.string.village_select));
        initRefreshLayout();
        et_village_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String inputStr = charSequence.toString();
                mData.clear();
                for(int j=0; j<mOriginalData.size(); j++){
                    if(mOriginalData.get(j).getVillage_name().contains(inputStr)){
                        mData.add(mOriginalData.get(j));
                    }
                }
                villageSelectAdapter.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        type = getIntent().getIntExtra(Events.TYPE_KEY,0);
        isCurrentArea = getIntent().getBooleanExtra("is_current",false);
        countyCode = getIntent().getStringExtra("county_code");
        String county_name = getIntent().getStringExtra("county_name");
        et_county_name.setText(county_name);

        LogUtil.d("countyCode:"+countyCode);
        LogUtil.d("county_name:"+county_name);

        initRecycleView();
        getVillage();
    }

    private void initRefreshLayout() {
        refresh_layout.setEnableLoadMore(false);
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishLoadMore(1500);
                getVillage();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishRefresh(1000);
                getVillage();
            }
        });
    }

    private void initRecycleView() {
        rv_data.setLayoutManager(new LinearLayoutManager(mContext));
        villageSelectAdapter = new VillageSelectAdapter(mContext,
                R.layout.item_village_select,mData);
        rv_data.setAdapter(villageSelectAdapter);
        villageSelectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                AreaV areaV = mData.get(position);
                Events.VillageSelectEvent villageSelectEvent = new Events.VillageSelectEvent();
                villageSelectEvent.setAreaV(areaV);
                villageSelectEvent.setType(type);
                RxBus.getDefault().post(villageSelectEvent);
                finish();
            }
        });
    }

    @OnClick({R.id.iv_select,R.id.et_county_name})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_select:
            case R.id.et_county_name:
                startActivity(CountySelectActivity.class);
                break;
        }
    }

    /**
     * 获取行政村数据
     *
     */
    private void getVillage() {
        if(isOnLine()){
            String villageName = et_village_name.getText().toString().trim();
            RetrofitFactory.getInstance().createApi(RetrofitApi.class).getVillage(countyCode,villageName)
                    .compose(RxScheduler.rxSchedulerTransform())
                    .subscribe(new BaseObserver<List<AreaV>>() {

                        @Override
                        protected void onStart() {
                            getLoadingDialog().show();
                        }

                        @Override
                        protected void onSuccess(List<AreaV> data) throws Exception {
                            mData.clear();
                            mData.addAll(data);
                            mOriginalData.clear();
                            mOriginalData.addAll(data);
                            villageSelectAdapter.notifyDataSetChanged();
                        }

                        @Override
                        protected void onFinish() {
                            getLoadingDialog().dismiss();
                        }
                    });
        }else{
//            ArrayList<AreaV> areaVList = LiteOrmUtil.getLiteOrm().query(AreaV.class);
            List<AreaV> areaVList = DBManager.get().areaVDao().getAll();
            mData.clear();
            mOriginalData.clear();
            if(isCurrentArea){
                List<WorkAreaResponse> workAreaResponseList = DBManager.get().workAreaResponseDao().getAll();
                if(workAreaResponseList.size() > 0){
                    List<WorkAreaResponse.VillageDataBean> village_data = workAreaResponseList.get(0).getVillage_data();
                    for(int j=0; j<areaVList.size(); j++){
                        if(!StringUtil.isEmpty(countyCode)){
                            if(areaVList.get(j).getCounty_code().equals(countyCode)){
                                //匹配工作区域的行政村
                                for (WorkAreaResponse.VillageDataBean villageDataBean : village_data) {
                                    if(areaVList.get(j).getVillage_code().equals(villageDataBean.getVillage_code())){
                                        mData.add(areaVList.get(j));
                                        mOriginalData.add(areaVList.get(j));
                                        break;
                                    }
                                }
                            }
                        }else{
                            //匹配工作区域的行政村
                            for (WorkAreaResponse.VillageDataBean villageDataBean : village_data) {
                                if(areaVList.get(j).getVillage_code().equals(villageDataBean.getVillage_code())){
                                    mData.add(areaVList.get(j));
                                    mOriginalData.add(areaVList.get(j));
                                    break;
                                }
                            }
                        }
                    }
                }
            }else{
                for(int j=0; j<areaVList.size(); j++){
                    if(!StringUtil.isEmpty(countyCode)){
                        if(areaVList.get(j).getCounty_code().equals(countyCode)){
                            mData.add(areaVList.get(j));
                            mOriginalData.add(areaVList.get(j));
                        }
                    }else{
                        mData.add(areaVList.get(j));
                        mOriginalData.add(areaVList.get(j));
                    }
                }
            }
            villageSelectAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 县选择回调
     * @param countySelectEvent
     */
    @Subscribe
    public void onCodeEvent(Events.CountySelectEvent countySelectEvent){
        AreaC areaC = countySelectEvent.getAreaC();
        et_county_name.setText(areaC.getCounty_name());
        countyCode = areaC.getCounty_code();
        getVillage();
    }

}
